package com.haochang.chunkvod.controller.adapter.order;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.SaleUtils;
import com.haochang.chunkvod.app.utils.VodDialog;
import com.haochang.chunkvod.controller.activity.order.EventDetailsActivity;
import com.haochang.chunkvod.model.order.ActiveInfo;
import com.haochang.chunkvod.model.order.FoodDetailInfo;
import com.haochang.chunkvod.model.order.FoodInfo;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.tools.vod.goods.ShoppingCartManager;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.view.vod.activity.ActivityDialogEnum;
import com.haochang.chunkvod.view.vod.activity.GoodsDetailsDialogActivity;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

/**
 * @author qintao
 *         created at 2016/6/24 11:15
 *         活动详情适配器
 */

public class ActiveExpandableAdapter extends BaseExpandableListAdapter
{
	private Context context;
	private List<ActiveInfo> groupList = new ArrayList<ActiveInfo>();
	private List<List<FoodInfo>> childList = new ArrayList<List<FoodInfo>>();

	public ActiveExpandableAdapter(Context context, List<ActiveInfo> groupList)
	{
		this.context = context;
		this.groupList.clear();
		this.childList.clear();
		if (!CollectionUtils.isEmpty(groupList))
		{
			this.groupList.addAll(groupList);
			this.childList.addAll(getChildList());
		}
	}

	public void setData(List<ActiveInfo> groupList)
	{
		this.groupList.clear();
		this.childList.clear();
		if (!CollectionUtils.isEmpty(groupList))
		{
			this.groupList.addAll(groupList);
			this.childList.addAll(getChildList());
		}
		ActiveExpandableAdapter.this.notifyDataSetChanged();
	}

	@Override
	public int getGroupCount()
	{
		return groupList.size();
	}

	@Override
	public int getChildrenCount(int groupPosition)
	{
		return this.childList.get(groupPosition).size();
	}

	@Override
	public Object getGroup(int groupPosition)
	{
		return groupList.get(groupPosition);
	}

	@Override
	public Object getChild(int groupPosition, int childPosition)
	{
		return childList.get(groupPosition).get(childPosition);
	}

	@Override
	public long getGroupId(int groupPosition)
	{
		return groupPosition;
	}

	@Override
	public long getChildId(int groupPosition, int childPosition)
	{
		return childPosition;
	}

	@Override
	public boolean hasStableIds()
	{
		return false;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition)
	{
		return false;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
	{
		GroupViewHolder groupViewHolder = null;
		if (null == convertView)
		{
			convertView = LayoutInflater.from(context).inflate(R.layout.item_active_detail_first_layout, parent, false);
			groupViewHolder = new GroupViewHolder();
			groupViewHolder.tv_foodName = (BaseTextView) convertView.findViewById(R.id.tv_foodName);
			groupViewHolder.tv_already = (BaseTextView) convertView.findViewById(R.id.tv_already);
			groupViewHolder.tv_totalPrice = (BaseTextView) convertView.findViewById(R.id.tv_totalPrice);
			groupViewHolder.img_pencil = (ImageView) convertView.findViewById(R.id.img_pencil);
			groupViewHolder.iv_direction = (ImageView) convertView.findViewById(R.id.iv_direction);
			convertView.setTag(groupViewHolder);
		} else
			groupViewHolder = (GroupViewHolder) convertView.getTag();
		final ActiveInfo info = groupList.get(groupPosition);
		groupViewHolder.tv_foodName.setText(info.getCn_name());
		JSONArray array = null;
		try
		{
			array = TextUtils.isEmpty(info.getCombos()) ? null : new JSONArray(info.getCombos());
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
		if (array != null && array.length() > 0)
		{
			groupViewHolder.tv_already.setVisibility(View.GONE);
			groupViewHolder.tv_totalPrice.setVisibility(View.GONE);
			groupViewHolder.img_pencil.setVisibility(View.GONE);
			groupViewHolder.iv_direction.setVisibility(View.VISIBLE);
		} else
		{
			groupViewHolder.tv_totalPrice.setText(String.valueOf(SaleUtils.getSaleString(info.getPrice()) + "/" + info.getUnit()));
			groupViewHolder.tv_already.setVisibility(View.VISIBLE);
			groupViewHolder.tv_totalPrice.setVisibility(View.VISIBLE);
			groupViewHolder.img_pencil.setVisibility(View.VISIBLE);
			groupViewHolder.iv_direction.setVisibility(View.GONE);
			groupViewHolder.tv_already.setText(Html.fromHtml("已选" + "<font color=#f04e39>" + info.getOrderNum() + "</font>" + "/" + info.getQuantity()));
			groupViewHolder.img_pencil.setTag(info);
			groupViewHolder.img_pencil.setOnClickListener(onBaseClickListener);
		}
		if (isExpanded)
			groupViewHolder.iv_direction.setImageResource(R.drawable.up);
		else
			groupViewHolder.iv_direction.setImageResource(R.drawable.down);
		return convertView;
	}

	@Override
	public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
	{
		ChildViewHolder childViewHolder = null;
		if (null == convertView)
		{
			convertView = LayoutInflater.from(context).inflate(R.layout.item_active_detail_second_layout, parent, false);
			childViewHolder = new ChildViewHolder();
			childViewHolder.tv_title = (BaseTextView) convertView.findViewById(R.id.tv_title);
			childViewHolder.lay_center_div = (LinearLayout) convertView.findViewById(R.id.lay_center_div);
			convertView.setTag(childViewHolder);
		} else
			childViewHolder = (ChildViewHolder) convertView.getTag();
		final FoodInfo info = this.childList.get(groupPosition).get(childPosition);
		List<FoodDetailInfo> detailInfoList = info.getFoodList();
		if (!CollectionUtils.isEmpty(detailInfoList))
		{
			childViewHolder.lay_center_div.removeAllViews();
			for (final FoodDetailInfo detailInfo : detailInfoList)
			{
				final RelativeLayout viewItem = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.item_package_detial_single, null);
				BaseTextView tv_foodName = (BaseTextView) viewItem.findViewById(R.id.tv_foodName);
				BaseTextView tv_num = (BaseTextView) viewItem.findViewById(R.id.tv_num);
				BaseTextView tv_price = (BaseTextView) viewItem.findViewById(R.id.tv_price);
				ImageView img_pencil_detail = (ImageView) viewItem.findViewById(R.id.img_pencil_detail);
				tv_foodName.setText(detailInfo.getName());
				if (!info.getType().equals("master") && detailInfo.getQuantity() > 0 && detailInfo.getQuantity() != 99999)
				{
					tv_foodName.append(Html.fromHtml("<font color=#a9a9a9>" + "(限选" + detailInfo.getQuantity() + detailInfo.getUnit() + ")" + "</font>"));
				}
				tv_price.setText(String.valueOf(SaleUtils.getSaleString(detailInfo.getPrice()) + "/" + detailInfo.getUnit()));
				if (info.getIs_present() == 1)
					tv_price.setVisibility(View.INVISIBLE);
				else
					tv_price.setVisibility(View.VISIBLE);
				childViewHolder.lay_center_div.addView(viewItem);
				img_pencil_detail.setTag(detailInfo);
				img_pencil_detail.setTag(R.id.active_food_info, info);
				img_pencil_detail.setOnClickListener(onBaseClickListener);
				if (info.getType().equals("master"))
				{
					try
					{
						JSONArray array = TextUtils.isEmpty(detailInfo.getTaste_types()) ? null : new JSONArray(detailInfo.getTaste_types());
						if (array != null && array.length() > 0)
							img_pencil_detail.setVisibility(View.VISIBLE);
						else
							img_pencil_detail.setVisibility(View.INVISIBLE);
					} catch (JSONException e)
					{
						e.printStackTrace();
					}
					tv_num.setText(String.valueOf("x" + detailInfo.getQuantity()));
				} else
				{
					img_pencil_detail.setVisibility(View.VISIBLE);
					if (detailInfo.getNumber() <= 0)
					{
						tv_num.setText("");
					} else
					{
						tv_num.setText(String.valueOf("x" + detailInfo.getNumber()));
					}
				}
				viewItem.setTag(detailInfo.getFood_id());
			}
			if (info.getType().equals("master"))
			{
				childViewHolder.tv_title.setText(info.getName());
			} else
			{
				childViewHolder.tv_title.setText(Html.fromHtml(info.getName() + "(已选" + "<font color=#f04e39>"
						+ ((info.getOrderNum() > 0) ? info.getOrderNum() : info.getDefaultNum()) + "</font>" + "/" + info.getQuantity() + ")"));
			}
		}
		return convertView;
	}

	private OnBaseClickListener onBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.img_pencil:
				ActiveInfo info = (ActiveInfo) v.getTag();
				onClickImgPencil(info);
				break;
			case R.id.img_pencil_detail:
				FoodDetailInfo detailInfo = (FoodDetailInfo) v.getTag();
				FoodInfo foodInfo = (FoodInfo) v.getTag(R.id.active_food_info);
				onClickImgPencilDetail(foodInfo, detailInfo);
				break;
			default:
				break;
			}
		}
	};

	private void onClickImgPencil(ActiveInfo info)
	{
		String flavor = info.getTaste_types();
		JSONArray array = null;
		try
		{
			array = TextUtils.isEmpty(flavor) ? null : new JSONArray(flavor);
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
		if (array != null && array.length() > 0)
		{
			Intent intent = new Intent(context, GoodsDetailsDialogActivity.class);
			intent.putExtra(IntentKey.ACTIVEINFO, info);
			intent.putExtra(IntentKey.SURPLUS_NUMBER, info.getQuantity());
			intent.putExtra(IntentKey.ORDERNUM, info.getOrderNum());
			intent.putExtra(IntentKey.FLAVOR, info.getFlavor());
			intent.putExtra(IntentKey.ACTIVITY_ENUM, ActivityDialogEnum.FLAVOR);
			((EventDetailsActivity) context).startActivityForResult(intent, IntentCode.ACTIVIE_REQUEST);
		} else
		{
			Intent intent = new Intent(context, GoodsDetailsDialogActivity.class);
			intent.putExtra(IntentKey.ACTIVEINFO, info);
			intent.putExtra(IntentKey.CUSTOM_DIALOG_LEFT_NAME, "数量");
			intent.putExtra(IntentKey.CUSTOM_DIALOG_CONTENT, info.getOrderNum() + "");
			intent.putExtra(IntentKey.SURPLUS_NUMBER, info.getQuantity());
			intent.putExtra(IntentKey.ACTIVITY_ENUM, ActivityDialogEnum.DEFAULT);
			((EventDetailsActivity) context).startActivityForResult(intent, IntentCode.ACTIVIE_REQUEST);
		}
	}

	private void onClickImgPencilDetail(FoodInfo info, FoodDetailInfo detailInfo)
	{
		String flavor = detailInfo.getTaste_types();
		JSONArray array = null;
		try
		{
			array = TextUtils.isEmpty(flavor) ? null : new JSONArray(flavor);
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
		if (array != null && array.length() > 0)
		{
			Intent intent = new Intent(context, GoodsDetailsDialogActivity.class);
			intent.putExtra(IntentKey.FOODINFO, detailInfo);
			intent.putExtra(IntentKey.SURPLUS_NUMBER, info.getQuantity() - info.getOrderNum() + detailInfo.getNumber());
			if (!info.getType().equals("master"))
			{
				int orderNum = ((info.getOrderNum() > 0) ? info.getOrderNum() : info.getDefaultNum());
				int number = (info.getQuantity() - orderNum + detailInfo.getNumber()) > detailInfo.getQuantity() ? detailInfo.getQuantity()
						: (info.getQuantity() - orderNum + detailInfo.getNumber());
				intent.putExtra(IntentKey.SURPLUS_NUMBER, number);
				intent.putExtra(IntentKey.ORDERNUM, detailInfo.getNumber());
			} else
			{
				intent.putExtra(IntentKey.SURPLUS_NUMBER, detailInfo.getQuantity());
				intent.putExtra(IntentKey.ORDERNUM, detailInfo.getQuantity());
			}
			intent.putExtra(IntentKey.FLAVOR, detailInfo.getFlavor());
			intent.putExtra(IntentKey.TYPE, info.getType());
			intent.putExtra(IntentKey.ACTIVITY_ENUM, ActivityDialogEnum.FLAVOR);
			((EventDetailsActivity) context).startActivityForResult(intent, IntentCode.ACTIVIE_REQUEST);
		} else
		{
			Intent intent = new Intent(context, GoodsDetailsDialogActivity.class);
			intent.putExtra(IntentKey.FOODINFO, detailInfo);
			intent.putExtra(IntentKey.CUSTOM_DIALOG_LEFT_NAME, "数量");
			intent.putExtra(IntentKey.CUSTOM_DIALOG_CONTENT, detailInfo.getNumber() + "");
			int orderNum = ((info.getOrderNum() > 0) ? info.getOrderNum() : info.getDefaultNum());
			int number = (info.getQuantity() - orderNum + detailInfo.getNumber()) > detailInfo.getQuantity() ? detailInfo.getQuantity()
					: (info.getQuantity() - orderNum + detailInfo.getNumber());
			intent.putExtra(IntentKey.SURPLUS_NUMBER, number);
			intent.putExtra(IntentKey.ACTIVITY_ENUM, ActivityDialogEnum.DEFAULT);
			((EventDetailsActivity) context).startActivityForResult(intent, IntentCode.ACTIVIE_REQUEST);
		}
	}

	/**
	 * 获取分组下FoodDetailInfo列表
	 *
	 * @return FoodDetailInfo列表
	 */
	private List<List<FoodInfo>> getChildList()
	{
		List<List<FoodInfo>> childrenList = new ArrayList<List<FoodInfo>>();
		for (int i = 0; i < groupList.size(); i++)
		{
			ActiveInfo activeInfo = groupList.get(i);
			if (!CollectionUtils.isEmpty(activeInfo.getFoodList()))
				childrenList.add(activeInfo.getFoodList());
			else
				childrenList.add(new ArrayList<FoodInfo>());
		}
		return childrenList;
	}

	/**
	 * activity返回数据刷新子数据
	 *
	 * @param info
	 */
	public void activityForResultRefreshChildData(FoodDetailInfo info)
	{

		for (int i = 0; i < groupList.size(); i++)
		{
			ActiveInfo activeInfo = groupList.get(i);
			if (!CollectionUtils.isEmpty(activeInfo.getFoodList()))
			{
				List<FoodInfo> foodInfoList = activeInfo.getFoodList();
				for (int k = 0; k < foodInfoList.size(); k++)
				{
					FoodInfo foodInfo = foodInfoList.get(k);
					if (foodInfo.getCombo_id().equals(info.getCombo_id()))
					{
						List<FoodDetailInfo> list = foodInfo.getFoodList();
						if (CollectionUtils.isEmpty(list))
							return;
						for (int j = 0; j < list.size(); j++)
						{
							FoodDetailInfo detailInfo = list.get(j);
							if (info.getFood_id().equals(detailInfo.getFood_id()))
							{
								detailInfo.setNumber(info.getNumber());
								detailInfo.setFlavor(info.getFlavor());
								break;
							}
						}
						int num = 0;
						for (int j = 0; j < list.size(); j++)
						{
							FoodDetailInfo detailInfo = list.get(j);
							num += detailInfo.getNumber();
						}
						foodInfo.setOrderNum(num);
						foodInfo.setDefaultNum(0);
						break;
					}
				}
			}
		}

		if (!CollectionUtils.isEmpty(childList))
		{
			childList.clear();
			childList.addAll(getChildList());
		}
		this.notifyDataSetChanged();
	}

	/**
	 * activity返回数据刷新组数据
	 *
	 * @param info 活动信息
	 */
	public void activityForResultRefreshGroupData(ActiveInfo info)
	{
		for (int k = 0; k < groupList.size(); k++)
		{
			ActiveInfo activeInfo = groupList.get(k);
			if (activeInfo.getGoods_id().equals(info.getGoods_id()))
			{
				activeInfo.setOrderNum(info.getOrderNum());
				activeInfo.setFlavor(info.getFlavor());
				break;
			}
		}
		this.notifyDataSetChanged();
	}

	/**
	 * 添加活动到购物车
	 * @param goodsInfo 商品信息
	 */
	public void addToGoods(final GoodsInfo goodsInfo)
	{
		boolean is_active_select = false;
		boolean is_goods_select = false;
		for (int i = 0; i < groupList.size(); i++)
		{
			ActiveInfo activeInfo = groupList.get(i);
			if (activeInfo.getOrderNum() < activeInfo.getQuantity() && CollectionUtils.isEmpty(activeInfo.getFoodList()))
			{
				is_active_select = true;
				break;
			}
		}
		for (int k = 0; k < childList.size(); k++)
		{
			final List<FoodInfo> infoList = childList.get(k);
			for (int i = 0; i < infoList.size(); i++)
			{
				FoodInfo foodInfo = infoList.get(i);
				if ((foodInfo.getOrderNum() > 0 ? foodInfo.getOrderNum() : foodInfo.getDefaultNum()) < foodInfo.getQuantity())
				{
					is_goods_select = true;
					break;
				}
			}
		}
		if (is_goods_select || is_active_select)
		{
			new VodDialog.Builder(context).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure)
					.cancelable(true).contentName("还有子餐品可选,确定添加吗？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
					{
						@Override
						public void onOnlyCancelClick()
						{

						}

						@Override
						public void onOkClick()
						{
							ShoppingCartManager.addActiveDetailToGoods(goodsInfo, groupList, true);
						}

						@Override
						public void onCancelClick()
						{

						}
					}).build().show();
		} else
		{
			ShoppingCartManager.addActiveDetailToGoods(goodsInfo, groupList, true);
		}
	}

	protected class GroupViewHolder
	{
		protected BaseTextView tv_foodName;
		protected BaseTextView tv_already;
		protected BaseTextView tv_totalPrice;
		protected ImageView img_pencil;
		protected ImageView iv_direction;
	}

	protected class ChildViewHolder
	{
		protected BaseTextView tv_title;
		protected LinearLayout lay_center_div;
	}

}
